<!--
  Copyright (c) 2020 classmate-sun
  [Software Name] is licensed under Mulan PSL v2.
  You can use this software according to the terms and conditions of the Mulan PSL v2.
  You may obtain a copy of Mulan PSL v2 at:
          http://license.coscl.org.cn/MulanPSL2
  THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
  EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
  MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
  See the Mulan PSL v2 for more details.
-->

<template>
  <el-dialog
    title="登录"
    :visible.sync="dialogVisible"
    width="425px"
    :before-close="beforeClose"
    :close-on-click-modal="true"
  >
    <el-form ref="form" :model="form" label-width="80px" :rules="rules">
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="form.userName" ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" show-password ></el-input>
      </el-form-item>
      <el-form-item label="验证码" prop="code" class="vcode">
        <el-input v-model="form.code" ></el-input>
        <div class="login-code" @click="refreshCode">
          <!--验证码组件-->
          <SIdentify :identifyCode="identifyCode"></SIdentify>
        </div>
    </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="danger" plain @click="gotoForget">忘记密码</el-button>
      <el-button type="success" plain @click="gotoRegister">立即注册</el-button>
      <el-button type="primary" @click="handleClick" :disabled="submitDisabled">登录</el-button>
    </span>
  </el-dialog>
</template>

<script>

import SIdentify from './SIdentify'
import {Encrypt,Decrypt} from "../assets/js/secret"
import {encrypt} from "@/assets/js/rsaUtil";
export default {
  name: "Login",
  components:{
    SIdentify
  },
  data() {
    return {
      //表单数据
      form: {
        userName: "",
        password: "",
        code: ""
      },
      identifyCodes: '1234567890',
      identifyCode: '',
      //表单验证
      rules: {
        //用户名验证
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            //数据类型
            type: "string",
            //正则规则
            pattern: /^[\w\u4e00-\u9fa5\uac00-\ud7ff\u0800-\u4e00\-]{2,7}$/,
            message: "请输入正确格式用户名",
            trigger: ["blur", "change"]
          }
        ],

        //密码验证
        password: {
          type: "string",
          validator: (rule, value, cb) => {
            if (value) {
              //验证密码是否符合规则
              if (/^[\w<>,.?|;':"{}!@#$%^&*()\/\-\[\]\\]{6,18}$/.test(value)) {
                cb();
              } else {
                cb(new Error("请输入正确格式密码"));
              }
            } else {
              cb(new Error("请输入密码"));
            }

            //在这里还需要触发确认密码的验证
            this.form.checkPwd && this.$refs.form.validateField("checkPwd");
          },
          required: true,
          trigger: ["blur", "change"]
        },
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { validator: (rule, value, callback) => {
              if (this.identifyCode !== value) {
                this.form.code = ''
                this.refreshCode()
                callback(new Error('请输入正确的验证码'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      },

      //登录过程禁用
      submitDisabled: false
    };
  },
  props: ["dialogVisible"],
  methods: {
    // getVCode() {
    //   getLoginVCode().then(res => {
    //     clearTimeout(this.login.timer);
    //     let t = 0;
    //     let fn = () => {
    //       t += 1000;
    //       if (t > res.data.time) {
    //         clearTimeout(this.login.timer);
    //         this.login.disabled = false;
    //         this.login.refreshText = "刷新";
    //       } else {
    //         this.login.disabled = true;
    //         this.login.refreshText =
    //           (((res.data.time - t) / 1000) | 0) + "s后可以刷新";
    //       }
    //     };
    //     this.login.timer = setInterval(fn, 1000);
    //     fn();
    //
    //     //更新图片
    //     this.login.svgText = res.data.data;
    //   });
    // },
    gotoRegister() {
      this.$emit("handleOpen", false);
    },
    gotoForget() {
      this.$emit("handleForget", false);
    },
    //登录方法
    handleClick() {
      this.submitDisabled = true;
      this.$refs['form'].validate(valid => {
        if (valid) {
          //验证都通过
          //let password = Encrypt(this.form.password);//密码加密

          var redisKey=this.form.userName;
          this.$ajax.post(this.$config.url+`/getRSAPublicKey`, {
            redisKey:redisKey
          }).then(res=>{
            if(res.data.status===this.$config.request_code_success){
              //秘钥生成成功,密码加密
              let password = encrypt(this.form.password,res.data.data);//密码加密
              this.login(password);
            }
          })

        } else {
          console.log("出错了");
          this.submitDisabled = false;
          //验证没通过
          return false;
        }
      });
    },

    login(password){
      this.$ajax.post(this.$config.url +'/ljblog/person/login', {
        "userName":this.form.userName,
        "password":password
      })
          .then(res => {
            if (res.data.status===this.$config.request_code_success) {
              //登录成功 调用vuex的action中的setUser存入用户对象
              this.$store.dispatch("setUser",res.data.data);
              //token
              this.$store.dispatch("setToken",res.data.data.token);
              this.$message({
                message: res.data.message,
                type: "success",
                duration: 2000
              });
              this.submitDisabled = false;
              this.$emit("handleClose");
              this.$emit("ifLogin");
            } else {
              this.submitDisabled = false;
              //登录失败
              this.$message({
                message: res.data.message,
                type: "error",
                duration: 2000
              });

            }
          })
          .catch(e => {
            this.$message({
              message: "登录失败请稍后再试~",
              type: "error",
              duration: 2000
            });
            this.submitDisabled = false;
          });
    },
    beforeClose(done) {
      this.$emit("handleClose");
    },
    makeCode(o, l) {
      for (let i = 0; i < l; i++) {
        this.identifyCode += this.identifyCodes[
            this.randomNum(0, this.identifyCodes.length)
            ]
      }
    },
    randomNum(min, max) {
      return Math.floor(Math.random() * (max - min) + min)
    },
    refreshCode() {
      this.identifyCode = ''
      this.makeCode(this.identifyCodes, 4)
    },
  },
  mounted() {
    // this.getVCode();
    this.refreshCode()
  },

};
</script>

<style scoped lang="less">
/deep/.el-dialog__body {
  padding: 20px 20px 0 20px;
}
.el-form {
  user-select: none;
  padding-right: 30px;

  .vcode {
    .el-input {
      float: left;
      width: 35%;
    }
    div.svg {
      float: left;
      width: 35%;
      height: 40px;
      /deep/ svg {
        width: 100% !important;
        height: 100% !important;
      }
    }
    .el-link {
      font-size: 12px;
    }
  }
}
</style>